<script setup>


import {
  crmCustomerDeleteAPI,
  crmCustomerExcelExportAPI,
  crmCustomerLockAPI,
  crmCustomerPoolDeleteAPI,
  crmCustomerPoolExcelExportAPI, crmCustomerReceiveAPI
} from "/src/api/crm/customer.js";
import {crmLeadsDeleteAPI, crmLeadsExcelExportAPI, crmLeadsTransformAPI} from "@/api/crm/leads.js";
import {crmContactsDeleteAPI, crmContactsExcelExportAPI} from "@/api/crm/contacts.js";
import {crmBusinessDeleteAPI, crmBusinessExcelExportAPI} from "@/api/crm/business.js";
import {crmContractDeleteAPI, crmContractExcelExportAPI} from "@/api/crm/contract.js";
import {crmReceivablesDeleteAPI, crmReceivablesExcelExportAPI} from "@/api/crm/receivables.js";
import {crmReceivablesPlanDeleteAPI, crmReceivablesPlanExcelExportAPI} from "@/api/crm/receivablesPlan.js";
import {crmProductDeleteAPI, crmProductExcelExportAPI, crmProductStatusAPI} from "@/api/crm/product.js";
import {downloadExcelWithResData} from "utils";
import {ElMessage, ElMessageBox} from "element-plus";
import {crmReturnVisitDeleteAPI} from "/src/api/crm/visit.js";
import {inject, reactive, computed, ref} from "vue";
import {
  crmOptionKey,
  elTableOptionKey,
  sceneDataKey
} from "/src/views/crm/componentsNew/SzCrud/keys.js";
import {useErpUserStore} from "../../../../../store/modules/usererp.js";
import TransferHandle from "../../SelectionHandle/TransferHandle.vue";
import TeamsHandle from "../../SelectionHandle/TeamsHandle.vue";
import AllocHandle from "../../SelectionHandle/AllocHandle.vue";
import DealStatusHandle from "../../SelectionHandle/DealStatusHandle.vue";
import PutPoolHandle from "../../SelectionHandle/PutPoolHandle.vue";


const crm = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.crm;
})

const teamsType = ref('') // 团队操作类型


const dialogShow = reactive({
  transferDialogShow: false,
  teamsDialogShow: false, // 团队操作提示框
  allocDialogShow: false, // 公海分配操作提示框
  dealStatusShow: false, // 成交状态修改框
  putPoolShow: false, // 客户放入公海
})


const elTableOption = inject(elTableOptionKey)
const crmOption = inject(crmOptionKey)

const emits = defineEmits(['actionClick', 'handle'])

/** 操作 */
function selectionBarClick(type) {
  console.log("type", type)
  // action 动作 handle 偏向结果
  emits('actionClick', {type: type, selection: elTableOption.selectionList})

  // 没有传入过数据，暂时不启用该代码
  // // 传出selection操作
  // if (props.handleFun) {
  //   props.handleFun(type)
  //   return
  // }

  if (type == 'transfer') {
    // 转移
    console.log("transfer")
    dialogShow.transferDialogShow = true
    console.log("dialogShow", dialogShow)
  } else if (type == 'export') {
    let params = {}
    let request = null
    if (crmOption.isSeas) {
      request = crmCustomerPoolExcelExportAPI
      params.poolId = crmOption.poolId
      params.ids = elTableOption.selectionList
          .map(item => item.customerId)
          .join(',')
    } else {
      request = {
        customer: crmCustomerExcelExportAPI,
        leads: crmLeadsExcelExportAPI,
        contacts: crmContactsExcelExportAPI,
        business: crmBusinessExcelExportAPI,
        contract: crmContractExcelExportAPI,
        receivables: crmReceivablesExcelExportAPI,
        receivablesPlan: crmReceivablesPlanExcelExportAPI,
        product: crmProductExcelExportAPI
      }[crmOption.crmType]
      params = elTableOption.selectionList.map(item => item[`${crmOption.crmType}Id`])
    }

    request(params).then(res => {
      downloadExcelWithResData(res)
    }).catch(() => {
    })
  } else if (type == 'transform' ||
      type == 'delete' ||
      type == 'lock' ||
      type == 'unlock' ||
      type == 'start' ||
      type == 'disable' ||
      type == 'get') {
    let message = ''
    if (type == 'transform') {
      message = '确定将这些线索转换为客户吗?'
    } else if (type == 'delete') {
      message = crmOption.isSeas ? '若客户下有联系人，联系人将一并删除。确定删除？' : `确定删除选中的${elTableOption.selectionList.length}项吗？`
    } else if (type == 'lock') {
      message = '确定要锁定这些客户吗？锁定后将不会掉入公海。'
    } else if (type == 'unlock') {
      message = '确定要解锁这些客户吗？'
    } else if (type == 'start') {
      message = '确定要上架这些产品吗?'
    } else if (type == 'disable') {
      message = '确定要下架这些产品吗?'
    } else if (type == 'get') {
      message = '确定要领取该客户吗?'
    }

    ElMessageBox.confirm(message, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      confirmHandle(type)
    }).catch(() => {
    })
  } else if (type == 'add_user') {
    // 团队操作
    teamsType.value = 'add'
    dialogShow.teamsDialogShow = true
  } else if (type == 'delete_user') {
    // 团队操作
    teamsType.value = 'delete'
    dialogShow.teamsDialogShow = true
  } else if (type == 'alloc') {
    // 公海分配操作
    dialogShow.allocDialogShow = true
  } else if (type == 'deal_status') {
    // 客户成交状态操作
    dialogShow.dealStatusShow = true
    console.log("dialogShow", dialogShow)
  } else if (type == 'put_seas') {
    // 客户放入公海
    dialogShow.putPoolShow = true
  }
}


function confirmHandle(type) {
  console.log("confirmHandle", type)
  if (type === 'lock' || type === 'unlock') {
    crmOption.loading = true
    crmCustomerLockAPI({
      status: type === 'lock' ? '2' : '1', // 1是正常 2 是锁定
      ids: elTableOption.selectionList.map(item => item.customerId).join(',')
    }).then(res => {
      crmOption.loading = false
      ElMessage.success({message: '操作成功'})
      emits('handle', {type: type})
    }).catch(() => {
      crmOption.loading = false
    })
  } else if (type === 'transform') {
    crmOption.loading = true
    crmLeadsTransformAPI(elTableOption.selectionList.map(item => item.leadsId)).then(res => {
      crmOption.loading = false
      ElMessage.success({message: '转化成功'})
      // 刷新待办
      const useCrmStore = useCrmStore();
      useCrmStore.GetMessageNum()
      // this.$store.dispatch('GetMessageNum')
      emits('handle', {type: type})
    }).catch(() => {
      crmOption.loading = false
    })
  } else if (type === 'start' || type === 'disable') {
    crmOption.loading = true
    crmProductStatusAPI({
      ids: elTableOption.selectionList.map(item => item.productId),
      status: type === 'start' ? '1' : '0'
    }).then(res => {
      crmOption.loading = false
      ElMessage.success({message: '操作成功'})
      emits('handle', {type: type})
    }).catch(() => {
      crmOption.loading = false
    })
  } else if (type === 'delete') {
    console.log("crmOption.crmType",crmOption.crmType)

    const ids = elTableOption.selectionList.map(item => item[crmOption.crmType + 'Id'])
    console.log("crmOption.crmType2",crmOption.crmType)
    const request = {
      leads: crmLeadsDeleteAPI,
      customer: crmOption.isSeas ? crmCustomerPoolDeleteAPI : crmCustomerDeleteAPI,
      contacts: crmContactsDeleteAPI,
      business: crmBusinessDeleteAPI,
      contract: crmContractDeleteAPI,
      receivables: crmReceivablesDeleteAPI,
      receivablesPlan: crmReceivablesPlanDeleteAPI,
      visit: crmReturnVisitDeleteAPI,
      product: crmProductDeleteAPI
    }[crmOption.crmType]
    console.log("crmOption.crmType3",crmOption.crmType)
    const params = {}
    if (crmOption.isSeas) {
      params.poolId = crmOption.poolId
    }
    params.ids = ids
    crmOption.loading = true
    request(crmOption.isSeas ? params : ids).then(res => {
      crmOption.loading = false
      if (res.data.code != 0) {

        ElMessage.error({message: res.data.msg})

      } else{
        ElMessage.success({message: '删除成功'})
      }
      emits('handle', {type: type})
    }).catch(() => {
      crmOption.loading = false
    })
  } else if (type === 'get') {
    // 领取
    crmOption.loading = true
    crmCustomerReceiveAPI({
      ids: elTableOption.selectionList.map(item => item.customerId),
      poolId: crmOption.poolId
    }).then(res => {
      crmOption.loading = false
      ElMessage.success({message: '操作成功'})
      // 刷新待办
      const useCrmStore = useCrmStore();
      useCrmStore.GetMessageNum()
      // this.$store.dispatch('GetMessageNum')
      emits('handle', {type: type})
    }).catch(() => {
      crmOption.loading = false
    })
  }
}


/** 获取展示items */
function getSelectionHandleItemsInfo() {
  const handleInfos = {
    transfer: {
      name: '转移',
      type: 'transfer',
      icon: 'transfer'
    },
    transform: {
      name: '转化为客户',
      type: 'transform',
      icon: 'transform'
    },
    export: {
      name: '导出选中',
      type: 'export',
      icon: 'export'
    },
    delete: {
      name: '删除',
      type: 'delete',
      icon: 'delete'
    },
    put_seas: {
      name: '放入公海',
      type: 'put_seas',
      icon: 'seas'
    },
    lock: {
      name: '锁定',
      type: 'lock',
      icon: 'lock'
    },
    unlock: {
      name: '解锁',
      type: 'unlock',
      icon: 'unlock'
    },
    add_user: {
      name: '添加团队成员',
      type: 'add_user',
      icon: 'add'
    },
    delete_user: {
      name: '移除团队成员',
      type: 'delete_user',
      icon: 'remove'
    },
    alloc: {
      name: '分配',
      type: 'alloc',
      icon: 'alloc'
    },
    get: {
      name: '领取',
      type: 'get',
      icon: 'receive'
    },
    start: {
      name: '上架',
      type: 'start',
      icon: 'shelves'
    },
    disable: {
      name: '下架',
      type: 'disable',
      icon: 'sold-out'
    },
    deal_status: {
      name: '更改成交状态',
      type: 'deal_status',
      icon: 's-status'
    },
    reset_invoice_status: {
      name: '重置开票信息',
      type: 'reset_invoice_status',
      icon: 'reset'
    },
    update: {
      name: '编辑',
      type: 'update',
      icon: 'edit'
    }
  }
  if (crmOption.crmType == 'leads') {
    return forSelectionHandleItems(handleInfos, [
      'transfer',
      'transform',
      'export',
      'delete'
    ])
  } else if (crmOption.crmType == 'customer') {
    if (crmOption.isSeas) {
      return forSelectionHandleItems(handleInfos, [
        'alloc',
        'get',
        'export',
        'delete'
      ])
    } else {
      return forSelectionHandleItems(handleInfos, [
        'transfer',
        'put_seas',
        'deal_status',
        'export',
        'delete',
        'lock',
        'unlock',
        'add_user',
        'delete_user'
      ])
    }
  } else if (crmOption.crmType == 'contacts') {
    return forSelectionHandleItems(handleInfos, [
      'transfer',
      'export',
      'delete',
      'add_user',
      'delete_user'
    ])
  } else if (crmOption.crmType == 'business') {
    return forSelectionHandleItems(handleInfos, [
      'transfer',
      'export',
      'delete',
      'add_user',
      'delete_user'
    ])
  } else if (crmOption.crmType == 'contract') {
    return forSelectionHandleItems(handleInfos, [
      'transfer',
      'export',
      'delete',
      'add_user',
      'delete_user'
    ])
  } else if (crmOption.crmType == 'receivables') {
    return forSelectionHandleItems(handleInfos, [
      'transfer',
      'export',
      'delete',
      'add_user',
      'delete_user'
    ])
  } else if (crmOption.crmType == 'receivablesPlan') {
    return forSelectionHandleItems(handleInfos, [
      'export',
      'update',
      'delete'
    ])
  } else if (crmOption.crmType == 'product') {
    return forSelectionHandleItems(handleInfos, [
      'transfer',
      'export',
      'delete',
      'start',
      'disable'
    ])
  } else if (crmOption.crmType == 'product') {
    return forSelectionHandleItems(handleInfos, [
      'export',
      'start',
      'disable'
    ])
  } else if (crmOption.crmType == 'visit') {
    return forSelectionHandleItems(handleInfos, [
      'delete'
    ])
  } else if (crmOption.crmType == 'invoice') {
    return forSelectionHandleItems(handleInfos, [
      'delete',
      'reset_invoice_status',
      'transfer'
    ])
  }
}


function forSelectionHandleItems(handleInfos, array) {
  const tempsHandles = []
  for (let index = 0; index < array.length; index++) {
    tempsHandles.push(handleInfos[array[index]])
  }
  return tempsHandles
}


const sceneData = inject(sceneDataKey)

// 判断是否展示
function whetherTypeShowByPermision(type) {
  if (type == 'transfer') {
    return sceneData.bydata == 'transform'
        ? false
        : crm.value[crmOption.crmType].transfer
  } else if (type == 'transform') {
    //已转化的线索
    return sceneData.bydata == 'transform'
        ? false
        : crm.value[crmOption.crmType].transform
  } else if (type == 'export') {
    if (crmOption.isSeas) {
      if (crmOption.poolId) {
        return props.poolAuth.excelexport
      }
      return crm.value.pool && crm.value.pool.excelexport
    }
    if (crm.value[crmOption.crmType]) {
      return crm.value[crmOption.crmType].excelexport
    } else {
      return true
    }
  } else if (type == 'delete') {
    if (crmOption.isSeas) {
      if (crmOption.poolId) {
        return props.poolAuth.delete
      }
      return crm.value.pool && crm.value.pool.delete
    }
    return crm.value[crmOption.crmType].delete
  } else if (type == 'put_seas') {
    // 放入公海(客户)
    return crm.value[crmOption.crmType].putinpool
  } else if (type == 'lock' || type == 'unlock') {
    // 锁定解锁(客户)
    return crm.value[crmOption.crmType].lock
  } else if (type == 'add_user' || type == 'delete_user') {
    // 添加 移除团队成员
    return crm.value[crmOption.crmType].teamsave
  } else if (type == 'alloc') {
    // 分配(公海)
    if (crmOption.poolId) {
      return props.poolAuth.distribute
    }
    return crm.value.pool && crm.value.pool.distribute
  } else if (type == 'get') {
    // 领取(公海)
    if (crmOption.poolId) {
      return props.poolAuth.receive
    }
    return crm.value.pool && crm.value.pool.receive
  } else if (type == 'start') {
    // 上架 下架(产品)
    for (let index = 0; index < elTableOption.selectionList.length; index++) {
      const element = elTableOption.selectionList[index]
      if (element.status == 1) {
        return false
      }
    }
    return crm.value[crmOption.crmType].status
  } else if (type == 'disable') {
    // 上架 下架(产品)
    for (let index = 0; index < elTableOption.selectionList.length; index++) {
      const element = elTableOption.selectionList[index]
      if (element.status == 0) {
        return false
      }
    }
    return crm.value[crmOption.crmType].status
  } else if (type == 'deal_status') {
    // 客户状态修改
    return crm.value[crmOption.crmType].dealStatus
  } else if (type == 'reset_invoice_status') {
    // 重置开票信息
    return crm.value[crmOption.crmType].resetInvoiceStatus && elTableOption.selectionList.length == 1
  } else if (type == 'update') {
    // 编辑
    return crm.value[crmOption.crmType].update && elTableOption.selectionList.length == 1
  }

  return true
}

// 子组件 回调的 结果
function handleCallBack(data) {
  emits('handle', {type: data.type})
}

</script>

<template>
  <div class="selected—title">已选中 <span class="selected—count">{{ elTableOption.selectionList.length }}</span> 项
  </div>
  <flexbox class="selection-items-box">
    <!-- todo 下面的el-button的icon使用不正确，目前无法显示图标 -->
    <el-button v-for="(item, index) in getSelectionHandleItemsInfo()" :key="index"
               v-show="whetherTypeShowByPermision(item.type)"
               :icon="item.icon"
               type="primary"
               @click="selectionBarClick(item.type)">{{ item.name }}
    </el-button>
  </flexbox>

  <template v-if="dialogShow.transferDialogShow">
    <TransferHandle
        :crm-type="crmOption.crmType"
        :selection-list="elTableOption.selectionList"
        v-model:dialogVisible="dialogShow.transferDialogShow"
        @handle="handleCallBack"/>
  </template>
  <template v-if="dialogShow.teamsDialogShow">
    <TeamsHandle :crm-type="crmOption.crmType" :type="teamsType"
                 :selection-list="elTableOption.selectionList"
                 :dialog-visible="dialogShow.teamsDialogShow"
                 @handle="handleCallBack"/>
  </template>
  <AllocHandle :crm-type="crmOption.crmType"
               :pool-id="crmOption.poolId"
               :selection-list="elTableOption.selectionList"
               :dialog-visible="dialogShow.allocDialogShow"
               @handle="handleCallBack"/>
  <DealStatusHandle :crm-type="crmOption.crmType"
                    :selection-list="elTableOption.selectionList"
                    v-model:visible="dialogShow.dealStatusShow"
                    @handle="handleCallBack"/>


  <PutPoolHandle :visible="dialogShow.putPoolShow"
                 :selection-list="elTableOption.selectionList"
                 @handle="handleCallBack"/>
</template>

<style scoped lang="scss">
.selected—title {
  flex-shrink: 0;
  padding-right: 20px;
  color: #333;

  .selected—count {
    color: $xr-color-primary;
  }
}


.selection-items-box {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0 15px;

  .el-button {
    color: #666;
    background-color: #f9f9f9;
    border-color: #e5e5e5;
    font-size: 12px;
    height: 28px;
    border-radius: 4px;

    :deep( i) {
      font-size: 12px;
      margin-right: 5px;
    }
  }

  .el-button--primary:hover {
    background: $xr-color-primary;
    border-color: $xr-color-primary;
    color: #ffffff;
  }

  .el-button + .el-button {
    margin-left: 15px;
  }
}
</style>